/**
 * 手写一个promise
 */

const p = new Promise()

//声明构造函数
function Promise(executor) {
  //添加属性
  this.PromiseState = 'pending';
  this.PromiseResult = null;
  //声明属性
  this.callbakc = {};
  //保存实例对象的this值,不然调用的时候用箭头函数的画,this的指向是window，到时候状态是没办法改变的。
  const self = this;//self _this that
  //resolve函数
  function resolve(data) {
    //判断状态
    if (self.PromiseState !== 'pending') return;
    //1. 修改对象的状态(PromiseState)
    self.PromiseState = 'fulfilled';//resolved
    //2. 设置对象的结果值(PromiseResult)
    self.PromiseResult = data;
    //调用成功的回调函数
    if (self.callbakc.onResolved) {
      self.callbakc.onResolved(data);
    }
  }
  //reject函数
  function reject(data) {
    //判断状态
    if (self.PromiseState !== 'pending') return;
    //1. 修改对象的状态(PromiseState)
    self.PromiseState = 'reject';//resolved
    //2. 设置对象的结果值(PromiseResult)
    self.PromiseResult = data;

    if (self.callbakc.onRejectd) {
      self.callbakc.onRejectd(data);
    }
  }
  try {
    // 同步调用
    executor(resolve, reject);
  } catch (e) {
    //修改promise对象状态为[失败]
    reject(e);
  }
}
//添加then方法
Promise.prototype.then = function (onResolved, onRejectd) {
  const self = this;
  //判断回调函数参数
  if (typeof onRejectd !== 'function') {
    onRejectd = reson => {
      throw reson
    }
  }
  if (typeof onResolved !== 'function') {
    onResolved = value => {
      throw value
    }
  }
  return new Promise((resolve, reject) => {

  })
  //调用回调函数
  if (this.PromiseState === 'fulflled') {
    onResolved(this.PromiseResult);
  }
  if (this.PromiseState === 'rejected') {
    onRejectd(this.PromiseResult);
  }
  //判断pending的状态
  if (this.PromiseState === 'pending') {
    //保存回调函数
    this.callbakc = {
      onResolved,
      onRejectd
    }

  }
}
//添加catch方法
Promise.prototype.catch = function (onRejectd) {
  return this.then(undefined, onRejectd);
}